"""
聊天室网络部分
"""
import time
import threading
import zmq

context = zmq.Context()

def init_server():
    socket = context.socket(zmq.REP)
    socket.bind("tcp://*:5555")
    pub_socket = context.socket(zmq.PUB)
    pub_socket.bind("tcp://*:5556")

    def server_loop():
        while True:
            #  Wait for next request from client
            message = socket.recv()
            pub_socket.send_string(f'chat:{str(message,encoding="ascii")}')
            socket.send(b'ok')

    threading.Thread(None,server_loop).start()

def init_client(ip_addr,get_input_msg,send_chat_list,name="default"):
    """
    ip_addr : 聊天室ip地址
    get_input_msg : 回调函数取的输入信息,如果没有输入就阻塞
    send_chat_list: 发送给聊天列表
    """
    socket = context.socket(zmq.REQ)
    socket.connect(f"tcp://{ip_addr}:5555")
    sub_socket = context.socket(zmq.SUB)
    sub_socket.connect(f"tcp://{ip_addr}:5556")
    sub_socket.setsockopt_string(zmq.SUBSCRIBE, "chat:")

    def sub_thread():
        while True:
            msg = sub_socket.recv_string()
            if len(msg)>5 and msg[:5]=='chat:':
                send_chat_list(msg[5:])
            else:
                send_chat_list(msg)
            time.sleep(1)

    def client_loop():
        while True:
            msg = get_input_msg()
            socket.send(bytes(f"{name}:{msg}",encoding='ascii'))
            socket.recv()

    threading.Thread(None,sub_thread).start()
    threading.Thread(None,client_loop).start()
